package com.wqd.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.wqd.behavior.dtos.CollectionBehaviorDto;
import com.wqd.behavior.pojos.ApCollectionBehavior;
import com.wqd.behavior.service.ApCollectionBehaviorService;
import com.wqd.common.constants.HotArticleConstants;
import com.wqd.model.common.dtos.ResponseResult;
import com.wqd.model.common.enums.AppHttpCodeEnum;
import com.wqd.model.mess.UpdateArticleMess;
import com.wqd.model.user.pojos.ApUser;
import com.wqd.utils.thread.ApThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;


    /**
     * 用户收藏行为
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        if(dto.getEntryId() == null){
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser apUser = ApThreadLocalUtil.getUser();
        if(apUser == null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(apUser.getId() == 0){
            return ResponseResult.okResult(405,"请先登录");
        }
        //查询用户是否已经保存了
        String collection_key = "USER_COLLECTION_" + dto.getEntryId();
        Boolean isCollection = redisTemplate.opsForHash().hasKey(collection_key, apUser.getId().toString());
        //如果已经收藏了,而且进行了收藏行为;或者是没收藏,却进行了取消收藏行为
        if((isCollection && dto.getOperation() == 0) || (!isCollection && dto.getOperation() == 1)){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //KafkaStream实时同步
        UpdateArticleMess articleMess = new UpdateArticleMess();
        articleMess.setArticleId(dto.getEntryId());
        articleMess.setType(UpdateArticleMess.UpdateArticleType.COLLECTION);

        //正常收藏行为
        if(!isCollection && dto.getOperation() == 0){
            //添加redis
            redisTemplate.opsForHash().put(collection_key,apUser.getId().toString(),"1");
            //添加mongodb
            ApCollectionBehavior apCollectionBehavior = new ApCollectionBehavior();
            apCollectionBehavior.setId(ObjectId.get().toHexString());
            apCollectionBehavior.setUserId(apUser.getId().longValue());
            apCollectionBehavior.setEntryId(dto.getEntryId());
            apCollectionBehavior.setType((short) 0);
            apCollectionBehavior.setCollectionTime(new Date());
            mongoTemplate.insert(apCollectionBehavior);

            //发送消息
            articleMess.setAdd(1);
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(articleMess));

            return ResponseResult.okResult("收藏成功");
        }
        //取消收藏
        if(isCollection && dto.getOperation() == 1){
            //删除redis
            redisTemplate.opsForHash().delete(collection_key,apUser.getId().toString());
            //删除mongodb
            mongoTemplate.remove(Query.query(Criteria.where("userId").is(apUser.getId().toString())
                    .and("entryId").is(dto.getEntryId())),ApCollectionBehavior.class);

            //发送消息
            articleMess.setAdd(-1);
            kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(articleMess));

            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return null;
    }
}
